#!/usr/bin/env python
# -*- coding: utf-8 -*-

from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
import re

class parseImages(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.list = []
  
  def handle_starttag(self, tag, attrs):
    if tag == 'img':
        for name,value in attrs:
            if name == 'src':
              self.list.append(value)
              
  def close(self):
    HTMLParser.close(self)
    return self.list
    
class parseURL(HTMLParser):
  def __init__(self, title):
    HTMLParser.__init__(self)
    self.url = ""
    self.title = re.sub(" ", "-", title.lower())
  
  def handle_starttag(self, tag, attrs):
    if tag == 'link':
        for name,value in attrs:
            if name == 'href':
              if self.title in value:
                self.url  = value
              
  def close(self):
    HTMLParser.close(self)
    return self.url

def getImages(html):
  lParser = parseImages()
  lParser.feed(html)
  return lParser.close()

def getTables(html):
  tables = []
  soup = BeautifulSoup(html)
  t = soup.findAll('table')
  for table in t:
    tb = []
    rows = table.findAll('tr')
    for tr in rows:
      row = []
      cols = tr.findAll('td')
      for td in cols:
        cell = re.sub("<td>|</td>", "", str(td))
        row.append(cell)
      tb.append(row)
      row = []
    tables.append(tb)
    tb = []
  return tables
  
def ParseTemplate(template, replace):
  for var in replace:
    expr = r"%"+var+"%"
    template = re.sub(expr, replace[var], template)
  return template

def TableToHTML(table):
  html = "<table cellspacing=\"20\"><tbody>"
  for row in table:
    html = html +"<tr align=\"center\">"
    for cell in row:
      html = html + "<td>" + cell + "</td>"
    html = html +"</tr>"
  html = html +"</tbody></table>"
  return BeautifulSoup(html).prettify()
